package com.lovi.user.controller;

import com.lovi.param.AddressListParams;
import com.lovi.param.AddressRemoveParam;
import com.lovi.param.AddressSaveParams;
import com.lovi.pojo.Address;
import com.lovi.user.service.serviceImpl.AddressServiceImpl;
import com.lovi.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/user/address")
@RestController
@Slf4j
public class AddressController {
    @Autowired
    private AddressServiceImpl addressService;

    @PostMapping("/list")
    public R list(@RequestBody @Validated AddressListParams addressListParams, BindingResult result){
        //参数校验
        if (result.hasErrors()){
            log.info("AddressController.list 结果为->{}", "参数错误");

            return R.fail("参数错误", addressListParams);
        }
        //返回找到的地址
        return addressService.list(addressListParams.getUserId());

    }

    /**
     * 新增地址
     * @param addressSaveParams
     * @param result
     * @return
     */
    @PostMapping("/save")
    public R add(@RequestBody @Validated AddressSaveParams addressSaveParams, BindingResult result){
        //参数校验
        if (result.hasErrors()){
            log.info("AddressController.add 结果为->{}", "参数错误");
            return R.fail("参数错误", addressSaveParams);
        }
        Address address = addressSaveParams.getAdd();
        address.setUserId(addressSaveParams.getUserId());
        //返回找到的地址
        return addressService.save(address);

    }

    @PostMapping("/remove")
    public R remove(@RequestBody @Validated AddressRemoveParam removeParam, BindingResult result){
        //参数校验
        if (result.hasErrors()){
            log.info("AddressController.remove 结果为->{}", "参数错误");
            return R.fail("参数错误");
        }
        //返回找到的地址
        return addressService.remove(removeParam.getId());

    }




}
